import { createRouter, createWebHashHistory } from "vue-router";
import { getCookie, setCookieWithSeconds } from "@/utils/public.js"; //公共方法
import { getMenuAndFunction, getToken, getUser } from "@/api/user.js"; //api接口

export let menuList = JSON.parse(sessionStorage.getItem("menuList")) || [];

// export const routeList = [{
//   path: '/basic',
//   name: '基本管理',
//   component: () => import('../views/basic/basic.vue'),
//   children: [
//     {
//       path: 'institution',
//       name: '机构管理',
//       component: () => import('../views/basic/institution.vue'),
//     },
//     {
//       path: 'user',
//       name: '用户管理',
//       component: () => import('../views/basic/user.vue'),
//     }
//   ]
// },
// {
//   path: '/app-platfor',
//   name: '平台应用管理',
//   component: () => import('../views/app-platfor/app-platfor.vue'),
//   children: [{
//     path: 'platform',
//     name: '平台管理',
//     component: () => import('../views/app-platfor/platform.vue'),
//   },
//   {
//     path: 'menu',
//     name: '菜单管理',
//     component: () => import('../views/app-platfor/menu.vue'),
//   },
//   {
//     path: 'func',
//     name: '功能管理',
//     component: () => import('../views/app-platfor/func.vue'),
//   },
//   {
//     path: 'roleGroup',
//     name: '角色组权限管理',
//     component: () => import('../views/app-platfor/roleGroup/index.vue'),
//     children: [{
//       path: 'add',
//       name: '新增组',
//       component: () => import('../views/app-platfor/roleGroup/add.vue'),
//     },
//     {
//       path: 'edit',
//       name: '编辑组',
//       component: () => import('../views/app-platfor/roleGroup/edit.vue'),
//     }
//     ]
//   },
//   ]
// },
// {
//   path: '/log-audit',
//   name: '日志审计',
//   component: () => import('../views/log-audit/log-audit.vue'),
//   children: [{
//     path: 'loginLog',
//     name: '登录日志',
//     component: () => import('../views/log-audit/loginLog.vue'),
//   },
//   {
//     path: 'oplog',
//     name: '操作日志',
//     component: () => import('../views/log-audit/oplog.vue'),
//   },
//   ]
// }
// ]

export const routes = [
  // {
  //   path: '/',
  //   redirect: '/basic/institution'
  // },
  {
    path: "/",
    name: "home",
    component: () => import("../views/home.vue"),
    // children: routeList
    children: [],
  },
  {
    path: "/notFound",
    name: "404",
    component: () => import("../views/notFound.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//获取token
const get_getToken = async (code) => {
  console.log(code);

  const res = await getToken({
    platformId: "e92ee242-497f-4077-9ba7-462265a6d03b",
    code: code,
  });
  if (res.code === 200) {
    console.log("获取token", res);
    // 名称 值 过期时间
    setCookieWithSeconds(
      "access_token",
      res.data.access_token,
      res.data.expires_in
    );
    setCookieWithSeconds(
      "refresh_token",
      res.data.refresh_token,
      res.data.expires_in
    );
    setCookieWithSeconds("uid", res.data.uid, res.data.expires_in);
    // 处理token时间
    var new_expires_in = "";
    if (res.data.expires_in) {
      var date = new Date();
      date.setTime(date.getTime() + res.data.expires_in * 1000);
      new_expires_in = date.toUTCString();
    }
    setCookieWithSeconds(
      "token_expires_in",
      new_expires_in,
      res.data.expires_in
    );
  }
};

// 前往登录页
//淮北
// const toLogin = () => {
//   const urlWithoutParams = window.location.href.replace(/(\?.*)?(#.*)?$/, "");

//   let new_Url =
//     "https://iam.ah.cegn.cn:2443/idp/authCenter/authenticate?redirect_uri=" +
//     urlWithoutParams +
//     "&response_type=code&client_id=5361d6c0638a408eb693755bf8f2554f&state=1";
//   window.location.href = new_Url;
// };
//淮南
const toLogin = () => {
  const urlWithoutParams = window.location.href.replace(/(\?.*)?(#.*)?$/, "");

  let new_Url =
    "https://iam.ah.cegn.cn:2443/idp/authCenter/authenticate?redirect_uri=" +
    urlWithoutParams +
    "&response_type=code&client_id=707a280e1ff4498e812e29a4d290740c&state=1";
  window.location.href = new_Url;
};

// 获取用户信息
const set_userInfo = async () => {
  const res = await getUser({
    platformId: "e92ee242-497f-4077-9ba7-462265a6d03b",
    access_token: getCookie("access_token"),
  });
  if (res.code === 200) {
    sessionStorage.setItem("userInfo", JSON.stringify(res.data));
    get_menuAndFunction();
  }
};
//获取菜单功能权限
export const get_menuAndFunction = async () => {
  const res = await getMenuAndFunction();
  if (res.code === 200 && res.data) {
    menuList = res.data;
    sessionStorage.setItem("menuList", JSON.stringify(res.data));
    let childtenList = set_routes(res.data);
    const homeRoute = router.getRoutes().find((route) => route.path === "/");

    router.addRoute({
      ...homeRoute,
      children: childtenList,
    });
    if (childtenList && childtenList[0].children) {
      router.push(childtenList[0].children[0].path);
    } else {
      router.push("/");
    }
  } else {
    router.push("/notFound");
  }
};

function transformArrayToObject(array) {
  const result = {};
  array.forEach((item) => {
    result[item.functionid] = true;
  });
  return result;
}

const set_routes = (menuList, menuId) => {
  return menuList.map((item) => {
    const route = {
      path: item.menuUrl,
      name: item.menuName,
      component: () =>
        import(`@/views/${menuId ? menuId : item.menuId}/${item.menuId}.vue`),
      meta: transformArrayToObject(item.roleAndFunctionVoList),
    };
    if (item.menuId == "roleGroup") {
      const route = {
        path: item.menuUrl,
        name: item.menuName,
        component: () =>
          import(
            `@/views/${menuId ? menuId : item.menuId}/${item.menuId}/index.vue`
          ),
        meta: transformArrayToObject(item.roleAndFunctionVoList),
        children: [
          {
            path: "add",
            name: "新增组",
            component: () => import("../views/app-platfor/roleGroup/add.vue"),
          },
          {
            path: "edit",
            name: "编辑组",
            component: () => import("../views/app-platfor/roleGroup/edit.vue"),
          },
        ],
      };
      return route;
    }
    // 如果当前菜单项有子菜单，递归调用 createRoutes
    if (item.children) {
      route.children = set_routes(item.children, item.menuId);
    }
    return route;
  });
};

if (menuList.length > 0) {
  let childtenList = set_routes(menuList);
  const homeRoute = router.getRoutes().find((route) => route.path === "/");

  router.addRoute({
    ...homeRoute,
    children: childtenList,
  });
  if (childtenList && childtenList[0].children) {
    router.push(childtenList[0].children[0].path);
  } else {
    router.push("/");
  }
}

// 路由拦截，判断是否需要登录
router.beforeEach(async (to, from, next) => {
  var url = window.location.href;
  const access_token = getCookie("access_token");
  if (access_token.length != 0) {
    //token存在
    let userinfo = sessionStorage.getItem("userInfo");
    if (!userinfo) {
      await set_userInfo();
    } else if (menuList.length == 0) {
      await set_userInfo();
    }
    next();
  } else {
    var queryString = url.split("?")[1];
    if (queryString) {
      var params = new URLSearchParams(queryString);
      var code = params.get("code");
      var state = params.get("state");
      if (code && code.length > 0) {
        sessionStorage.setItem("code", code);
        console.log(code);

        await get_getToken(code);
        if (getCookie("access_token").length != 0) {
          await set_userInfo(); //获取用户信息
          next(); //进入系统
        } else {
          toLogin(); //进入登录页
        }
      } else {
        toLogin(); //进入登录页
      }
    } else {
      toLogin(); //进入登录页
    }
  }
});

export default router;
